package com.sense.kukoo.biz_media.view

import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.gyf.immersionbar.ImmersionBar
import com.sense.feel.common.utils.ToastUtils
import com.sense.kukoo.biz_media.R
import com.sense.kukoo.biz_media.adapter.MediaChannelAdapter
import com.sense.kukoo.biz_media.databinding.BizMediaActivityMediaChannelBinding
import com.sense.kukoo.biz_media.vm.MediaChannelViewModel
import com.sense.kukoo.common.anim.BottomMotionAnimHelper
import com.sense.kukoo.common.constant.ARouterUrl
import com.sense.kukoo.common.event.LoginSuccessEvent
import com.sense.kukoo.common.media.Kukoo
import com.sense.kukoo.common.media.bean.LocalMediaListItemBean
import com.sense.kukoo.common.media.watcher.UserWatcher
import com.sense.kukoo.common.mvvm.view.BaseMvvmActivity
import com.sense.kukoo.common.repo.Repo
import com.sense.kukoo.common.repo.http.bean.IndexContentBean
import com.sense.kukoo.common.repo.http.bean.UserInfoBean
import com.sense.kukoo.common.utils.ApplicationContext
import com.sense.kukoo.common.utils.ClipboardUtil
import com.sense.kukoo.common.wiget.dialog.BottomLoginDialog
import com.sense.kukoo.common.wiget.state.NetworkErrorState
import com.sense.kukoo.lib_logger.LoggerManager
import com.zy.multistatepage.state.SuccessState
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

@Route(path = ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_CHANNEL_ACTIVITY)
class MediaChannelActivity : BaseMvvmActivity<MediaChannelViewModel, BizMediaActivityMediaChannelBinding>() {

    private val TAG: String = javaClass.simpleName
    private val mAnimHelper = BottomMotionAnimHelper()

    var mCurrentMusic: LocalMediaListItemBean? = null
    var mCurrentPlayState: Int = UserWatcher.MusicStateWatcher.STATE_NOT_PLAYING

    @JvmField
    @Autowired(name = ARouterUrl.KEY_FROM)
    var from: String? = null

    private lateinit var mAdapter:MediaChannelAdapter

    override fun responseVM(action: Int) {}

    override fun getLayoutId(): Int = R.layout.biz_media_activity_media_channel

    override fun getViewModelClass(): Class<MediaChannelViewModel> = MediaChannelViewModel::class.java

    override fun initStatusBar() {
        ImmersionBar.with(this)
            .transparentStatusBar()
            .navigationBarColor(com.sense.kukoo.common_design.R.color.bg_background)
            .statusBarDarkFont(true)
            .navigationBarDarkIcon(true)
            .fitsSystemWindows(false)
            .init()
    }

    override fun initData() {
        //
        ARouter.getInstance().inject(this)
        mViewModel.setFromData(from!!.toLong())
        //
        mBinding.lifecycleOwner = this
        mBinding.vm = mViewModel
        //
        bindAction(mViewModel.action_back){
            mAnimHelper.animateToFinish()
        }
        bindAction(mViewModel.action_more){
            ToastUtils.showToast("todo - more")
        }
        bindAction(mViewModel.action_finishRefres){
            mBinding.refreshLayout.finishRefresh()
        }
        bindAction(mViewModel.action_finishLoadMore){
            mBinding.refreshLayout.finishLoadMore()
        }
        bindAction(mViewModel.action_network_error){
            mBinding.multiStateContainer.show<NetworkErrorState> {
                it.onRetry {
                    mViewModel.onNetworkRetry()
                }
            }
        }
        bindData(mViewModel.data_channelContent){
            mBinding.multiStateContainer.show<SuccessState>()
            mAdapter.list = it
            mAdapter.notifyDataSetChanged()
        }
        bindData(mViewModel.data_enableLoadMore){
            mBinding.refreshLayout.setEnableLoadMore(it)
        }
    }

    override fun initView() {
        mAdapter = MediaChannelAdapter(mutableListOf(), mListener)
        mBinding.recyclerView.adapter = mAdapter

        val linearLayoutManager = LinearLayoutManager(this)
        mBinding.recyclerView.layoutManager = linearLayoutManager
        mBinding.refreshLayout.setOnRefreshListener {
            //OnRefresh
            mViewModel.onRefreshData()
        }
        mBinding.refreshLayout.setOnLoadMoreListener {
            //OnLoadMore
            mViewModel.onLoadMoreData()
        }
        //
        initUserId()
        //
        mBinding.refreshLayout.autoRefresh()
        //弹出动画
        val first = ApplicationContext.dp2px(800F).toFloat()
        mAnimHelper.init(mBinding.flChannelRoot, mBinding.clChannelContentRoot, first){ finish() }
        mAnimHelper.animateToStart()
    }

    override fun onBackPressed() {
        mAnimHelper.animateToFinish()
    }

    private fun initUserId(){
        val userID = Repo.user.get()?.id ?: 0
        mAdapter.setCurrentUserId(userID)
    }

    private val mListener = object : MediaChannelAdapter.IndexContentEventListener {
        override fun onItemClick(data: IndexContentBean) {
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_DESCRIPTION_ACTIVITY)
                .withString(ARouterUrl.KEY_FROM, "${data.id}")
                .navigation()
        }

        override fun onChannelClick(data: IndexContentBean) {
            //Channel页面就是当前页面，不做调整
        }

        override fun onBtnPlayClick(data: IndexContentBean) {
            if(mCurrentMusic?.idOfChapter() == data.id){
                //当前的
                when (mCurrentPlayState) {
                    UserWatcher.MusicStateWatcher.STATE_ERROR_RETRYING,
                    UserWatcher.MusicStateWatcher.STATE_SEEKING,
                    UserWatcher.MusicStateWatcher.STATE_PREPARE,
                    UserWatcher.MusicStateWatcher.STATE_PLAYING -> {
                        Kukoo.input.pause()
                    }
                    /*UserWatcher.MusicStateWatcher.STATE_NOT_PLAYING ->{}
                    UserWatcher.MusicStateWatcher.STATE_PAUSE ->{}*/
                    else -> {
                        Kukoo.input.start()
                    }
                }
            }else{
                //非当前的
                Kukoo.input.play(LocalMediaListItemBean(data))
            }
        }

        override fun onFollowClick(data: UserInfoBean) {
            if (BottomLoginDialog.autoCheckAndLogin(this@MediaChannelActivity)) {
                mViewModel.onFollowClick(data)
            }
        }

        override fun onChannelUserIdClick(data: UserInfoBean) {
            val idStr = "${data.id}"
            if (ClipboardUtil.copy(idStr)) {
                ToastUtils.showToast(ApplicationContext.getString(com.sense.kukoo.common_i18n.R.string.hint_copy_success))
            }
        }
    }

    private val mWatcher = object: UserWatcher.MusicStateWatcher{

        override fun onMusicChanged(music: LocalMediaListItemBean) {
            mCurrentMusic = music
            mAdapter.setCurrentMusic(music)
        }

        override fun onPlayTimeChanged(currentInt: Int, totalInt: Int, current: String, total: String) {}

        override fun onPlayPercentChanged(percent: Int) {}

        override fun onPlayStateChanged(state: Int) {
            mCurrentPlayState = state
            mAdapter.setCurrentPlayState(state)
        }

        override fun onPlaySpeedChanged(speed: Float) {}

        override fun onPlayListChanged() {}
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: LoginSuccessEvent) {
        initUserId()
        mViewModel.onRefreshData()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
        Kukoo.watcher.register(mWatcher)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        Kukoo.watcher.unregister(mWatcher)
    }
}